package org.domon.manager.sys.controller;

import org.domon.manager.base.handler.BaseController;
import org.domon.manager.common.WebConstants;
import org.domon.manager.model.ResultObject;
import org.domon.manager.sys.model.UserInfo;
import org.domon.manager.sys.service.SysMenuService;
import org.domon.manager.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.alibaba.fastjson.JSONObject;

@Controller
@SessionAttributes({ WebConstants.USER, WebConstants.USER_JSON })
public class UserController extends BaseController {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysMenuService sysMenuService;

	/**
	 * 登陆页面
	 * 
	 * @return
	 */
	@RequestMapping("/login")
	private String login() {
		return "login";
	}

	/**
	 * 登陆页面鉴权
	 * 
	 * @param loginName
	 * @param password
	 * @param captcha
	 * @param sessionStatus
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/login/auth")
	public ResultObject<?> loginAuth(String loginName, String password, String captcha, SessionStatus sessionStatus, Model model) {
		ResultObject<UserInfo> resultObject = new ResultObject<UserInfo>();

		UserInfo userInfo = sysUserService.userAuth(loginName, password);
		if (userInfo == null) {
			logger.info("用户[{}]登陆失败", loginName);
			resultObject.setSuccess(false);
			resultObject.setMsg("登录失败：用户名或密码错误！");
			sessionStatus.setComplete();
			return resultObject;
		} else {
			logger.info("用户[{}]登陆成功", loginName);
			resultObject.setSuccess(true);
			resultObject.setMsg("登录成功！");
			model.addAttribute(WebConstants.USER, userInfo);
			model.addAttribute(WebConstants.USER_JSON, JSONObject.toJSONString(userInfo));
		}
		return resultObject;
	}

	/**
	 * 登出系统
	 * 
	 * @param userInfo
	 * @param sessionStatus
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(UserInfo userInfo, SessionStatus sessionStatus) {
		logger.info("用户[{}]登出系统", userInfo.getUserName());
		sessionStatus.setComplete();
		return "login";
	}

	/**
	 * 首页
	 * 
	 * @param userInfo
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	public String index(UserInfo userInfo, Model model) {
		return "index";
	}
}
